﻿using Newtonsoft.Json;
using QDSpider.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WeiTap.Web;

namespace QDSpider.database
{
    public class ConnectionManager
    {
        /// <summary>
        /// 获取连接字符串
        /// </summary>
        /// <param name="dataBase"></param>
        /// <returns></returns>
        public static string GetConString(string dataBase)
        {
            //从接口中获取数据库连接
            var www = new HttpFire("http://api.711688.com.cn/wx/ajax_dyb.ashx?action=getdbconfig");
            var json = www.GetString();

            if (string.IsNullOrEmpty(json) || json.Length < 3)
                throw new Exception("数据库连接加载失败");

            var jsonModel = JsonConvert.DeserializeObject<JsonModel<DbString>>(json);
            if (jsonModel == null || jsonModel.Data == null)
                throw new Exception("数据库连接解密失败");

            //去除前2个字符qd后，反序列化,   再base64解码
            var dbString = Encoding.UTF8.GetString(Convert.FromBase64String(jsonModel.Data.Substring(2)));
            var dbModel = JsonConvert.DeserializeObject<DbString>(dbString);
            if (dbModel == null)
                throw new Exception("数据库连接解密失败");

            return
                $"Data Source={dbModel.server},{dbModel.port};Initial Catalog={dataBase};User ID={dbModel.userid};Password={dbModel.password};Pooling=true;MAX Pool Size=30;Min Pool Size=5;Connection Lifetime=30;";
        }
    }

    public class JsonModel<T>
    {
        public int Code { get; set; }
        public string Message { get; set; }
        public string Data { get; set; }
    }

}